<template>
	<view style="padding: 10rpx;">
		<view>
			<uni-tag :type="type==item.tagValue?'success':'primary'" :text="item.tagName" v-for="item in tags" :key="item.id" style="margin: 5rpx;" @click="setType(item)" />
		</view>
		<view class="container">
			<view class="example">
				<uni-forms ref="baseForm" :rules="rules" :modelValue="baseFormData">
					<uni-forms-item label="标题" required name="title">
						<uni-easyinput v-model="baseFormData.title" placeholder="请输入标题" />
					</uni-forms-item>
					<uni-forms-item label="内容" required name="content">
						<uni-easyinput type="textarea" v-model="baseFormData.content" placeholder="请输入内容" />
					</uni-forms-item>
					<uni-forms-item label="文件上传">
						<uni-file-picker limit="1" :auto-upload="true" @select="select" @success="success"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
				<button type="primary" @click="submit('baseForm')">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tags:null,
				type:null,
				pic:null,
				baseFormData:{
					name:'',
					age:''
				},
				rules: {
						title: {
							rules: [{
								required: true,
								errorMessage: '标题不能为空'
							}]
						},
						content: {
							rules: [{
								required: true,
								errorMessage: '内容不能为空'
							}]
						}
					},
			}
		},
		onLoad() {
			this.getTags()
		},
		methods: {
			getTags(){
				this.$http.get('/tags').then(res=>{
					if(res.data.code!=200) return
					this.tags=res.data.data
				})
			},
			setType(val){
				this.type=val.tagValue
			},
			select(file){
				console.log(file)
				this.$http({
					method:'post',
					url:'/upload',
					headers:{
						'content-type':'multipart/form-data'
					},
					data:{
						file:file.tempFiles[0].file
					}
				}).then(res=>{
					this.pic=res.data.data.path
				})
			},
			success(){
				console.log(111)
			},
			submit(ref){
				if(!this.type) return uni.showToast({
										title: '请选择标签'
									})
				this.$refs[ref].validate().then(res => {
					this.$http.post('/publish',{
						title:this.baseFormData.title,
						content:this.baseFormData.content,
						pic:this.pic,
						createTime:new Date(),
						tagValue:this.type
					}).then(res=>{
						uni.showToast({
							title: `发布成功`
						})
						uni.navigateTo({
							url:'/pages/index/index'
						})
					})
				}).catch(err => {
					console.log('err', err);
				})
			}
		}
	}
</script>

<style>
.container{
	margin-top: 20rpx;
}
</style>
